package com.th.campusmatchbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.th.campusmatchbackend.common.BaseResponse;
import com.th.campusmatchbackend.common.ErrorCode;
import com.th.campusmatchbackend.common.ResultUtils;
import com.th.campusmatchbackend.exception.BusinessException;
import com.th.campusmatchbackend.model.domain.User;
import com.th.campusmatchbackend.model.dto.UserMatchByGeoRequest;
import com.th.campusmatchbackend.model.request.UpdateTagRequest;
import com.th.campusmatchbackend.model.request.UserLoginRequest;
import com.th.campusmatchbackend.model.request.UserQueryRequest;
import com.th.campusmatchbackend.model.request.UserRegisterRequest;
import com.th.campusmatchbackend.model.vo.UserVO;
import com.th.campusmatchbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.th.campusmatchbackend.contant.UserContant.USER_LOGIN_STATE;


/**
 * 用户接口
 *
 * @author taoha
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if(userRegisterRequest == null){
            //return ResultUtils.error(ErrorCode.PARAMS_ERROR);
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String username = userRegisterRequest.getUsername();

        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"输入不能为空");
        }
        long result =  userService.userRegister(userAccount, userPassword, checkPassword,username);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if(userLoginRequest == null){
             return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
            User user =  userService.userLogin(userAccount, userPassword,request);
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout( HttpServletRequest request){
        if(request  == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false)  List<String> tagNameList){
        if(CollectionUtils.isEmpty(tagNameList)){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        List<User> userList = userService.searchUsersByTags(tagNameList);

        return ResultUtils.success(userList);
    }


    @GetMapping("/search")
    public  BaseResponse<List<User>> searchUsers(String username,HttpServletRequest request){
        //仅管理员可查询
        if(!userService.isAdmin(request)){
            //return ResultUtils.success(new ArrayList<>());
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        List<User> userList = userService.list(queryWrapper);
        //java8
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id,HttpServletRequest request){
        //仅管理员可删除
        if(!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize,long pageNum ,HttpServletRequest request){
        User loginUser   = userService.getCurrentUser(request);

        String redisKey = String.format("taohahu:user:recommendUsers:%s:%s",loginUser.getId(),pageNum);
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        //如果有缓存直接读取
        Page<User>  userPage = (Page<User>)operations.get(redisKey);
        if(userPage!=null){
            return  ResultUtils.success(userPage);
        }
        //无缓存，查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum,pageSize),queryWrapper);
        //写缓存，30秒过期
        try {
            operations.set(redisKey,userPage,30000, TimeUnit.MILLISECONDS);
        }catch (Exception e){
            log.error("redis set  key error",e);
        }

        return ResultUtils.success(userPage);

    }


    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request){
        //判断参数是否合法
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //鉴权
        User loginUser  =  userService.getCurrentUser(request);

        System.out.println("loginUser:" + loginUser);

        int result = userService.updateUser(user,loginUser,request);
        return ResultUtils.success(result);
    }

    @PostMapping("/update/tags")
    public BaseResponse<Integer> updateTags(@RequestBody UpdateTagRequest tagRequest, HttpServletRequest request){
        if (tagRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.getCurrentUser(request);
        int updateTag = userService.updateTagById(tagRequest, currentUser, request);
        String redisKey = String.format("taohahu:user:recommendUsers:%s",currentUser.getId());
        redisTemplate.delete(redisKey);

        return ResultUtils.success(updateTag);


    }

    @GetMapping("current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userobj = request.getSession().getAttribute(USER_LOGIN_STATE);

        User  currentUser = (User) userobj;
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NULL_LOGIN);
        }
        long userId = currentUser.getId();
        // todo 校验要用户是否合法
        User safetyUser =  userService.getSafetyUser(userService.getById(userId));
        return ResultUtils.success(safetyUser);

    }

    /**
     * 获取最匹配用户
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num,HttpServletRequest request) {
        if(num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        User user = userService.getCurrentUser(request);
        return ResultUtils.success(userService.matchUsers(num,user));

    }

    @GetMapping("/query")
    public BaseResponse<UserVO> queryUser(@RequestParam long showUserId){
        if(showUserId<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(showUserId);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return ResultUtils.success(userVO);
    }

    @GetMapping("/friends")
    public BaseResponse<List<User>> getFriends(HttpServletRequest request) {
        User currentUser = userService.getCurrentUser(request);
        List<User> getUser = userService.getFriendsById(currentUser);
        return ResultUtils.success(getUser);
    }

    @PostMapping("/deleteFriend/{id}")
    public BaseResponse<Boolean> deleteFriend(@PathVariable("id") Long id, HttpServletRequest request) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "好友不存在");
        }
        User currentUser = userService.getCurrentUser(request);
        boolean deleteFriend = userService.deleteFriend(currentUser, id);
        return ResultUtils.success(deleteFriend);
    }

    @PostMapping("/searchFriend")
    public BaseResponse<List<User>> searchFriend(@RequestBody UserQueryRequest userQueryRequest, HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        User currentUser = userService.getCurrentUser(request);
        List<User> searchFriend = userService.searchFriend(userQueryRequest, currentUser);
        return ResultUtils.success(searchFriend);
    }

    /**
     * 查找附近的人
     * @param userMatchByGeoRequest
     * @param request
     * @return
     */
    @GetMapping("/match/geo")
    public BaseResponse<List<User>> matchUsersByGeo(UserMatchByGeoRequest userMatchByGeoRequest, HttpServletRequest request) {

        if (userMatchByGeoRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        double pointLng = userMatchByGeoRequest.getPointLng();
        double pointLat = userMatchByGeoRequest.getPointLat();
        int num = userMatchByGeoRequest.getNum();
        int matchRange = userMatchByGeoRequest.getMatchRange();

        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User user = userService.getCurrentUser(request);

        Point userPoint = new Point(pointLng, pointLat);

        List<User> userList = userService.matchGeoUsers(num, userPoint, matchRange, user);

        return ResultUtils.success(userList);

    }


}
